import 'chromedriver'; // 确保 chromedriver 二进制在 PATH 中
import { Builder } from 'selenium-webdriver';
import chrome from 'selenium-webdriver/chrome.js';

const HEADLESS_DEFAULT = process.env.E2E_HEADLESS ?? 'true';

export const BASE_URL = process.env.E2E_BASE_URL ?? 'http://localhost:5173';

export async function ensureServerUp(timeoutMs = 60000) {
  const start = Date.now();
  let lastError;
  while (Date.now() - start < timeoutMs) {
    try {
      const controller = new AbortController();
      const id = setTimeout(() => controller.abort(), 3000);
      const res = await fetch(BASE_URL, { method: 'GET', signal: controller.signal });
      clearTimeout(id);
      if (res.ok) return;
      lastError = new Error(`HTTP ${res.status}`);
    } catch (e) {
      lastError = e;
    }
    await new Promise(r => setTimeout(r, 1000));
  }
  throw new Error(`等待前端服务 ${BASE_URL} 启动超时: ${lastError?.message || lastError}`);
}

export async function createDriver() {
  const options = new chrome.Options();

  if (HEADLESS_DEFAULT !== 'false') {
    options.addArguments('--headless=new');
  }

  options.addArguments(
    '--window-size=1280,720',
    '--disable-gpu',
    '--disable-dev-shm-usage',
    '--no-sandbox',
    '--disable-infobars',
    '--disable-extensions'
  );

  return new Builder()
    .forBrowser('chrome')
    .setChromeOptions(options)
    .build();
}

